package com.wywah.yunduo.security.supports.form;

import com.wywah.yunduo.security.properties.YunduoSecurityProperties;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;

public class FormLoginConfigurer extends AbstractHttpConfigurer<FormLoginConfigurer, HttpSecurity> {
    private final YunduoSecurityProperties securityProperties;
    @Override
    public void init(HttpSecurity http) throws Exception {
        http.formLogin(formLogin -> {
                    formLogin.loginPage(securityProperties.getLoginEndpoint());
                    formLogin.loginProcessingUrl("/token/form");
                    formLogin.failureHandler(new FormAuthenticationFailureHandler());
                    formLogin.successHandler(new AuthenticationSuccessHandler(){
                        @Override
                        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {


                            System.out.println("================");
                        }
                    });

                })
                .logout(logout -> logout.logoutSuccessHandler(new SsoLogoutSuccessHandler())
                        .deleteCookies("JSESSIONID")
                        .invalidateHttpSession(true)) // SSO登出成功处理

                .csrf(AbstractHttpConfigurer::disable);
    }

    public FormLoginConfigurer(YunduoSecurityProperties yunduoSecurityProperties) {
        this.securityProperties = yunduoSecurityProperties;
    }
}
